package com.ziq.zcamp.place

import android.animation.Animator
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ScreenUtils
import com.gmlive.camp.dialog.share.ShareDialog
import com.google.android.material.appbar.AppBarLayout
import com.qweather.sdk.bean.weather.WeatherDailyBean
import com.qweather.sdk.view.QWeather
import com.zhpan.bannerview.BaseBannerAdapter
import com.zhpan.bannerview.BaseViewHolder
import com.ziq.base.base.BaseActivity
import com.ziq.base.extension.*
import com.ziq.base.manager.MMKVManager
import com.ziq.base.utils.SystemBarUtil
import com.ziq.base.utils.permission.PermissionUtil
import com.ziq.zcamp.R
import com.ziq.zcamp.api.service.UserAccountService
import com.ziq.zcamp.api.service.getFinalUrl
import com.ziq.zcamp.bean.place.LocationInfo
import com.ziq.zcamp.bean.place.PlaceDetail
import com.ziq.zcamp.bean.place.VrInfo
import com.ziq.zcamp.bean.post.CampInfo
import com.ziq.zcamp.bean.post.ImageInfo
import com.ziq.zcamp.bean.post.PostingDetail
import com.ziq.zcamp.bean.product.PlaceProduct
import com.ziq.zcamp.constant.KEY_PLACE_DETAIL_PUNCH_RECOMMEND_TIPS
import com.ziq.zcamp.databinding.ActivityPlaceDetailBinding
import com.ziq.zcamp.dialog.share.ActionItem
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.*
import com.ziq.zcamp.mine.PersonalHomePageActivity
import com.ziq.zcamp.post.MapActivity
import com.ziq.zcamp.post.PostingAdapter
import com.ziq.zcamp.util.PictureUtil
import com.ziq.zcamp.view.CustomLinePagerIndicator
import com.ziq.zcamp.view.PlaceDetailPagerTitleView
import com.ziq.zcamp.view.SafetySimpleDraweeView
import com.ziq.zcamp.view.StatusView
import com.ziq.zcamp.view.layoutmanager.CustomStaggeredGridLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import net.lucode.hackware.magicindicator.FragmentContainerHelper
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import java.text.DecimalFormat
import javax.inject.Inject
import kotlin.math.floor


@AndroidEntryPoint
class PlaceDetailActivity : BaseActivity() {

    companion object {
        const val DETAIL_ID = "detail_id"
        const val DETAIL_NAME = "detail_name"
        const val DETAIL_SOURCE = "detail_source"
        const val DETAIL_MODE = "detail_mode"
        const val DETAIL_SORTING = "detail_sorting"
        fun open(context: Context, id: Int?, name:String, source:String, mode:String = "",sorting:String = "", onSetting: (intent:Intent)->Unit = {}){
            val intent = Intent(context, PlaceDetailActivity::class.java)
            intent.putExtra(DETAIL_ID, id)
            intent.putExtra(DETAIL_NAME, name)
            intent.putExtra(DETAIL_SOURCE, source)
            intent.putExtra(DETAIL_MODE, mode)
            intent.putExtra(DETAIL_SORTING, sorting)
            onSetting.invoke(intent)
            GlobalContextManager.startActivity(context, intent)
        }
    }

    @Inject
    lateinit var mUserAccountService: UserAccountService

    val binding: ActivityPlaceDetailBinding by binding()
    private val mViewModel: PlaceDetailViewModel by viewModels()

    private var source :String? = null
    private var mode :String? = null
    private var sorting :String? = null
    private var detailId :Int = 0
    private var detailName :String? = null
    private var detailUid = 0

    var statusBarHeight = 0

    var adapter : PlaceDetailAdapter? = null
    var currentBannerIndex = 0
    var isTabClick = false

    private val delayFinish :Runnable by lazy{
        Runnable{
            finish()
            overridePendingTransition(0, 0)
        }
    }

    var isTopPostModelValid = false
    var topPostModelTipsRunnable = Runnable {
        binding.placeDetailPostBannerViewTips.visibility = View.GONE
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SystemBarUtil.immerseStatusBar(this.window, statusBarIsLight = true)
        binding.root
        try {
            if(intent.hasExtra(DETAIL_ID)){
                val target = intent.getIntExtra(DETAIL_ID, 0)
                detailId  = if(target > 0) target else 0
            }
            if(intent.hasExtra(DETAIL_NAME)){
                detailName = intent.getStringExtra(DETAIL_NAME)
            }
            if(intent.hasExtra(DETAIL_SOURCE)){
                source = intent.getStringExtra(DETAIL_SOURCE)
            }
            if(intent.hasExtra(DETAIL_MODE)){
                mode = intent.getStringExtra(DETAIL_MODE)
            }
            if(intent.hasExtra(DETAIL_SORTING)){
                sorting = intent.getStringExtra(DETAIL_SORTING)
            }
        }catch (e:Exception){
            println("$e")
        }
        mViewModel.detailId = detailId
        statusBarHeight = BarUtils.getStatusBarHeight()
        val lp = binding.titleBarContent.layoutParams as ConstraintLayout.LayoutParams
        lp.topMargin = statusBarHeight
        binding.titleBarContent.layoutParams = lp

        binding.collapsingToolbarLayout.minimumHeight = statusBarHeight + 44.dp

        binding.back.click {
            finish()
        }

        binding.btnShare.click {
            onShare()
        }

        UserManager.instance.campCollect.observe(this, Observer {
            it?.let {
                if(it.containsKey(detailId)){
                    binding.btnCollect.isSelected = it[detailId] == 0
                }
            }
        })
        UserManager.instance.userFollowRelation.observe(this, Observer {
            if(adapter?.parametersGroup?.placeDetail != null && (adapter?.itemCount?:0) > 0){
                adapter?.notifyItemChanged((adapter?.itemCount?:1) - 1)
            }
        })

        binding.recyclerView.layoutManager = CustomStaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        val postingItemWidth = (ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_31)) / 2
        adapter = PlaceDetailAdapter(this, ScreenUtils.getScreenWidth(), postingItemWidth)
        adapter?.campId = detailId
        adapter?.placeProductActionListener = object : PlaceProductActionListener {
            override fun onProductClick(item: PlaceProduct) {
                PlaceProductDetailActivity.open(this@PlaceDetailActivity, item.commodity_id, item, "camp_detail", fromCampDetail = true)
            }
        }
        adapter?.postingAdapterAction = object : PostingAdapter.PostingAdapterAction {
            override fun itemClick(item: PostingDetail) {
                PostManager.navigateToDetailActivity(this@PlaceDetailActivity, item)
            }

            override fun userInfoClick(item: PostingDetail) {
                PersonalHomePageActivity.open(this@PlaceDetailActivity, item.user?.uid?:0)
            }
        }

        initMagicIndicator()

        binding.recyclerView.adapter = adapter
        val targetHeight = 110.dp
        binding.appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            val remain = appBarLayout.totalScrollRange + verticalOffset
            var alpha = 0f
            if(remain <= targetHeight){
                alpha = 1f - (remain.toFloat() / targetHeight) + 0.2f
                if(alpha > 1f){
                    alpha -= 0.2f
                }
                if(alpha > 1f){
                    alpha = 1f
                }
            }
            updateTitleBar(alpha)
        })
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if(isTabClick){
                    return
                }
                updateTabStatus()
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    binding.recyclerView.removeCallbacks(showRunnable)
                    binding.recyclerView.postDelayed(showRunnable, 1000)
                    updateTabStatus()
                    isTabClick = false
                }else if(newState == RecyclerView.SCROLL_STATE_DRAGGING || newState == RecyclerView.SCROLL_STATE_SETTLING){
                    startPostingBtnHide()
                }
            }

        })

        mViewModel.statusShow.observe(this, Observer<Int> {
            when(it){
                StatusView.IDLE -> {
                    binding.statusView.setStatus(StatusView.IDLE)
                }
                StatusView.LOADING -> {
                    binding.statusView.setStatus(StatusView.LOADING)
                }
                StatusView.NO_DATA -> {
                    binding.statusView.setStatus(StatusView.NO_DATA,
                        isCenter = false,
                        marginTop = 60.dp,
                        imgSrc = R.drawable.pic_no_content_camp,
                        imgWidth = 235.dp,
                        imgHeight = 151.dp,
                        msg = "还没有相关内容哦~"
                    )
                }
                StatusView.NET_ERROR -> {
                    binding.statusView.setStatus(StatusView.NET_ERROR, updateActionBtn = { btn ->
                        btn.click {
                            mViewModel.onRefresh(true)
                        }
                    })
                }
            }
        })
        mViewModel.dimiss.observe(this, Observer {
            GlobalContextManager.mainHandler.postDelayed(delayFinish,500)
        })

        mViewModel.placeDetail.observe(this, Observer<PlaceDetail> {
            it?.let {
                updateUi(it)
                updateLocation(it)
                updateAppraise(it)
            }
        })
        mViewModel.punchRecommendList.observe(this, Observer {
            if(it?.isNotEmpty() == true){
                isTopPostModelValid = true
                binding.placeDetailPostBannerView.updateData(mViewModel.detailId?:0, mutableListOf<PostingDetail>().apply {
                    addAll(it)
                })
            } else {
                isTopPostModelValid = false
            }
        })

        mViewModel.actList.observe(this, Observer {
            adapter?.setActData(it)
            updateScrollTab()
        })
        mViewModel.productList.observe(this, Observer {
            adapter?.setProductData(it?.list, it.show_num?:8, mViewModel.couponList.value)
            updateScrollTab()
        })

        mViewModel.listRequestFinished.observe(this, Observer<Boolean> {
            if(it){
                binding.refreshLayout.finishRefresh()
                binding.refreshLayout.finishLoadMore()
            }
        })

        mViewModel.listHasMore.observe(this, Observer<Boolean> {
            if(it){
                binding.refreshLayout.resetNoMoreData()
            } else {
                binding.refreshLayout.setNoMoreData(true)
            }
        })

        mViewModel.postingList.observe(this) {
            adapter?.setPostingData(it)
            updateScrollTab()
        }

        binding.refreshLayout.setOnRefreshListener {
            mViewModel.onRefresh(false)
        }
        binding.refreshLayout.setOnLoadMoreListener {
            mViewModel.onLoadMore()
        }
        binding.refreshLayout.setEnableLoadMore(false)
        mViewModel.onRefresh(true)
        refreshPostingVersion = DataManager.postingVersion.value
    }


    @SuppressLint("SetTextI18n")
    fun updateUi(placeDetail: PlaceDetail){
        detailName = placeDetail.camp?.camp_name
        detailUid = placeDetail.user?.uid?:0

        UserManager.instance.apply {
            if(isLogin.value == true){
                getFollowRelation(detailUid)
            }
        }

        binding.btnCollect.isSelected = placeDetail.is_collect?:false
        binding.btnCollect.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    UserManager.instance.apply {
                        if(isLogin.value == true){
                            if(binding.btnCollect.isSelected){
                                collectCamp(detailId?:0, 1)
                            } else {
                                collectCamp(detailId?:0, 0)
                            }
                        }
                    }
                }
            })
        }

        binding.btnPostingClick.click {
            publishPosting(placeDetail)
        }

        binding.btnToTopClick.click {
            binding.btnToTop.visibility = View.GONE
            handleTabSelected(0, true)
        }

        updateBanner(placeDetail)


        adapter?.setData(placeDetail)

        //QWeather获取上下文是为了获取applicationContext，
        // 其中weatherDataPresenters为静态对象Context传递进去后会被引用到其中的成员变量引发内存泄漏
        if(PrivacyManager.isAgreedPrivacy()){
            QWeather.getWeather7D(GlobalContextManager.appContext, "${placeDetail.camp?.longitude?:""},${placeDetail.camp?.latitude?:""}", object : QWeather.OnResultWeatherDailyListener {
                override fun onSuccess(weatherDailyBean: WeatherDailyBean) {
                    if(weatherDailyBean.daily.isNotEmpty()){
                        val item = weatherDailyBean.daily[0]
                        adapter?.setWeatherData(item)
                    }
                }

                override fun onError(throwable: Throwable?) {
                    Log.e("QWeather", "$throwable")
                }
            }
            )
        }

    }

    var bannerAdapter : PlaceDetailBannerAdapter? = null
    fun updateBanner(placeDetail: PlaceDetail){
        val imageList: MutableList<ImageInfo> = mutableListOf() // banner
        var vr : VrInfo? = null
        if(placeDetail.camp?.images?.isNotEmpty() == true){
            imageList.addAll(placeDetail.camp?.images!!)
        }
        if(imageList.size > 0){
            val imageInfo = imageList.get(0)
            val height = PictureUtil.calculatePlacePictureHeight(ScreenUtils.getScreenWidth(), imageInfo.width, imageInfo.height)
            val params = binding.flBanner.layoutParams as ViewGroup.LayoutParams
            params.width = ScreenUtils.getScreenWidth()
            params.height = height
            binding.flBanner.layoutParams = params

            val params2 = binding.placeDetailPostBannerView.layoutParams as ConstraintLayout.LayoutParams
            params2.width = ScreenUtils.getScreenWidth()
            params2.height = height
            binding.placeDetailPostBannerView.layoutParams = params2

            val params3 = binding.placeDetailPostBannerViewTips.layoutParams as ConstraintLayout.LayoutParams
            params3.height = height
            binding.placeDetailPostBannerViewTips.layoutParams = params3

            binding.coordinatorLayout.requestLayout()
        }
        if(placeDetail.camp?.vr?.exist_vr == true){
            vr = placeDetail.camp?.vr
        }


        if(vr != null){
            binding.llBannerTab.visibility = View.VISIBLE
        } else {
            binding.llBannerTab.visibility = View.GONE
        }
        if(bannerAdapter == null){
            bannerAdapter = PlaceDetailBannerAdapter(this)
            binding.bannerViewPager.adapter = bannerAdapter
            binding.bannerViewPager.isUserInputEnabled = true
            binding.bannerViewPager.offscreenPageLimit = 1
            binding.bannerViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    updateBannerTab(position)
                }
            })
            bannerAdapter?.onImagePageChangeCallback = { position, size ->
                updateBannerTabImage(position, size)
            }
        }


        bannerAdapter?.setBannerData(imageList, vr)
        binding.tvBannerTabVr.click {
            currentBannerTab = 0
            binding.bannerViewPager.setCurrentItem(0)
            bannerAdapter?.notifyItemChanged(1)
        }
        binding.tvBannerTabImage.click {
            binding.bannerViewPager.setCurrentItem(1)
        }


        var start = false
        bannerAdapter?.bannerGroup?.onNestedPreScroll = { coordinatorLayout: CoordinatorLayout,
                                                          child: View,
                                                          target: View,
                                                          dx: Int,
                                                          dy: Int,
                                                          consumed: IntArray,
                                                          type: Int ->
            if(isTopPostModelValid){
                if(!start && dx > 0){
                    start = true
                    GlobalContextManager.mainHandler.removeCallbacks(topPostModelTipsRunnable)
                    binding.placeDetailPostBannerViewTips.visibility = View.GONE
                    binding.placeDetailPostBannerView.setXOffset(dx.toFloat())
                    consumed[0] = dx
                } else if(start){
                    binding.placeDetailPostBannerView.setXOffset(dx.toFloat())
                    consumed[0] = dx
                }
            }

        }
        bannerAdapter?.bannerGroup?.onStopNestedScroll = { coordinatorLayout: CoordinatorLayout,
                                                           child: View,
                                                           target: View,
                                                           type: Int ->
            if(isTopPostModelValid && start){
                start = false
                binding.placeDetailPostBannerView.stopXOffset()
            }
        }
        bannerAdapter?.bannerGroup?.onImageBannerPageSelected = { index, size ->
            if(isTopPostModelValid){
                GlobalContextManager.mainHandler.removeCallbacks(topPostModelTipsRunnable)
                if(index == size - 1){
                    if(!MMKVManager.mmkv.decodeBool(KEY_PLACE_DETAIL_PUNCH_RECOMMEND_TIPS, false)){
                        binding.placeDetailPostBannerViewTips.visibility = View.VISIBLE
                        GlobalContextManager.mainHandler.postDelayed(topPostModelTipsRunnable, 2000)
                        MMKVManager.mmkv.encode(KEY_PLACE_DETAIL_PUNCH_RECOMMEND_TIPS, true)
                    }
                } else {
                    binding.placeDetailPostBannerViewTips.visibility = View.GONE
                }
            }
        }
        binding.placeDetailPostBannerView.resetXOffset()
        binding.placeDetailPostBannerView.onShowActionListener = {
            binding.llBannerTab.visibility = View.GONE
            binding.placeDetailPostBannerViewBg.visibility = View.VISIBLE
        }
        binding.placeDetailPostBannerView.onDismissActionListener = {
            binding.placeDetailPostBannerViewBg.visibility = View.GONE
            if(vr != null){
                binding.llBannerTab.visibility = View.VISIBLE
            } else {
                binding.llBannerTab.visibility = View.GONE
            }
        }
        binding.placeDetailPostBannerViewBg.setOnTouchListener { _, _ ->
            binding.placeDetailPostBannerView.onDismiss()
            return@setOnTouchListener true
        }

        requestPunchRecommendData(placeDetail)
    }

    fun requestPunchRecommendData(placeDetail: PlaceDetail){
        if((placeDetail.camp?.images?.size?:0) > 1){
            mViewModel.requestPunchRecommendList()
        } else {
            isTopPostModelValid = false
        }
    }

    var currentBannerTab = 0
    fun updateBannerTab(tab:Int){
        currentBannerTab = tab
        if(tab == 0){
            binding.tvBannerTabVr.setTextColor(Color.parseColor("#FFFFFF"))
            binding.tvBannerTabVr.setBackgroundResource(R.drawable.bg_place_detail_banner_tab_selected)
            binding.tvBannerTabVr.setPadding(8.dp, 0, 8.dp, 0)
            binding.tvBannerTabImage.setTextColor(Color.parseColor("#333333"))
            binding.tvBannerTabImage.setBackgroundResource(R.drawable.bg_place_detail_banner_tab_nor)
            binding.tvBannerTabImage.setPadding(4.dp, 0, 8.dp, 0)
            binding.tvBannerTabImage.text = "图片"
        } else {
            binding.tvBannerTabVr.setTextColor(Color.parseColor("#333333"))
            binding.tvBannerTabVr.setBackgroundResource(R.drawable.bg_place_detail_banner_tab_nor)
            binding.tvBannerTabVr.setPadding(8.dp, 0, 4.dp, 0)
            binding.tvBannerTabImage.setTextColor(Color.parseColor("#FFFFFF"))
            binding.tvBannerTabImage.setBackgroundResource(R.drawable.bg_place_detail_banner_tab_selected)
            binding.tvBannerTabImage.setPadding(8.dp, 0, 8.dp, 0)
            updateBannerTabImage(bannerAdapter?.bannerGroup?.currentImagePosition?:0, bannerAdapter?.bannerGroup?.imageSize?:0)
        }
    }

    fun updateBannerTabImage(imagePosition:Int, imageSize:Int){
        if(currentBannerTab == 1){
            binding.tvBannerTabImage.text = "图片 ${imagePosition + 1}/$imageSize"
        }
    }

    @SuppressLint("SetTextI18n")
    fun updateLocation(placeDetail: PlaceDetail?){

        if(mViewModel.greenCampAgreeStatus.value != null && mViewModel.greenCampAgreeStatus.value!!.status ==0){
            binding.ivAddressLock.visibility = View.VISIBLE
            binding.locationName.visibility = View.GONE
            binding.ivAddressLock.click {
//                GreenCampEntranceDialog(this, commit = {
//                    it.dismiss()
//                    greenCampLauncher.launch(Intent(this, GreenCampProtocolActivity::class.java).apply {
//                        putExtra("from", "location")
//                    })
//                }).show()
            }
            binding.locationNavigation.click {
//                GreenCampEntranceDialog(this, commit = {
//                    it.dismiss()
//                    greenCampLauncher.launch(Intent(this, GreenCampProtocolActivity::class.java).apply {
//                        putExtra("from", "location")
//                    })
//                }).show()
            }
        } else {
            binding.ivAddressLock.visibility = View.GONE
            binding.locationName.visibility = View.VISIBLE
            binding.locationName.text = placeDetail?.camp?.location_addr
            binding.locationName.click {
                if(placeDetail?.camp?.longitude?.isNotEmpty() == true && placeDetail.camp?.latitude?.isNotEmpty() == true){
                    val locationInfo: LocationInfo = LocationInfo()
                    locationInfo.site = placeDetail.camp?.location_addr
                    locationInfo.longitude = placeDetail.camp?.longitude
                    locationInfo.latitude = placeDetail.camp?.latitude
                    PermissionUtil.requestLocationPermission(this, onGrant = {
                        MapActivity.open(this, locationInfo)
                    }, onReject = {
                    }, onRemind = {
                    })
                } else {
                    val errMsg = GlobalContextManager.getString(R.string.data_error)
                    Toast.makeText(GlobalContextManager.appContext, errMsg, Toast.LENGTH_SHORT).show()
                }
            }
            binding.locationNavigation.click {
                navigationClick()
            }
        }


        val hasPhoneNumber = placeDetail?.camp?.telephone?.isNotEmpty() == true || placeDetail?.camp?.cellphone?.isNotEmpty() == true
        val hasWechat = placeDetail?.camp?.wechat?.isNotEmpty() == true
        val hasContact = UserManager.instance.imConf.value?.open_im == true
        if(hasPhoneNumber || hasWechat || hasContact){
            binding.locationPhone.visibility = View.VISIBLE
        }
        binding.locationPhone.click {
//            showContactDialog(placeDetail)
        }

        var hasTopLabel = placeDetail?.camp?.rank?.country_rank != null || placeDetail?.camp?.rank?.province_rank != null
        binding.llTopLabel.isVisible = hasTopLabel
        if(hasTopLabel){
            if(placeDetail?.camp?.rank?.country_rank != null){
                binding.tvTopLabel.text = "全国热门营地榜·Top${placeDetail?.camp?.rank?.country_rank?.rank}"
            } else if(placeDetail?.camp?.rank?.province_rank != null){
                binding.tvTopLabel.text = "${placeDetail?.camp?.rank?.province_rank?.district?.name}热门营地榜·Top${placeDetail?.camp?.rank?.province_rank?.rank}"
            }
            binding.ivCampInfoBgMask.visibility = View.VISIBLE
            binding.clCampInfoDetail.setPadding(0, 23.dp, 0, 16.dp)
        } else {
            binding.ivCampInfoBgMask.visibility = View.GONE
            binding.clCampInfoDetail.setPadding(0, 16.dp, 0, 16.dp)
        }
        binding.llTopLabel.click {
            if(placeDetail?.camp?.rank?.country_rank != null){
                PlaceRankActivity.open(this, "camp_detail")
            } else if(placeDetail?.camp?.rank?.province_rank != null){
                PlaceRankActivity.open(this, "camp_detail")
            }
        }
        binding.campName.text = placeDetail?.camp?.camp_name
        binding.campNameTop.text = placeDetail?.camp?.camp_name
        if((placeDetail?.score?.camp_score?:0) > 0){
            binding.llScore.visibility = View.VISIBLE
            binding.tvTotalScore.text = DecimalFormat("0.0").format((placeDetail?.score?.camp_score?:0) / 10f)
            binding.rbTotalScore.rating = roundDown((placeDetail?.score?.camp_score?:0)).toFloat()
            binding.llScore.click {
//                CampAppraiseActivity.open(this,placeDetail?.camp?.id?:0)
            }
        } else {
            binding.llScore.visibility = View.GONE
        }
    }

    private fun roundDown(num : Int) : Double{
        val a = num /10.0
        return if (a - floor(a) >= 0.5){
            floor(a) +0.5
        }else{
            floor(a)
        }
    }

    private fun updateAppraise(it: PlaceDetail) {
        adapter?.setAppraiseData(it.score)
        updateScrollTab()
    }

    private fun updateScrollTab(){
        if(adapter?.hasAppraiseCard() == true){
            if(!titles.contains(title_appraise)){
                titles.add(titles.size - 1, title_appraise)
            }
        } else {
            if(titles.contains(title_appraise)){
                titles.remove(title_appraise)
            }
        }
        if(adapter?.hasBookingCard() == true || adapter?.hasActCard() == true){
            if(!titles.contains(title_booking)){
                titles.add(0, title_booking)
            }
        } else {
            if(titles.contains(title_booking)){
                titles.remove(title_booking)
            }
        }
        binding.magicIndicator.navigator?.notifyDataSetChanged()

        if(titles.size > 1){
            binding.llScrollTab.visibility = View.VISIBLE
            binding.collapsingToolbarLayout.minimumHeight = statusBarHeight + 44.dp + 42.dp
        } else {
            binding.llScrollTab.visibility = View.GONE
            binding.collapsingToolbarLayout.minimumHeight = statusBarHeight + 44.dp
        }

    }

    var refreshPostingVersion :Int? = null
    override fun onResume() {
        super.onResume()
        if(refreshPostingVersion == null && DataManager.postingVersion.value != null){
            mViewModel.onRefreshPosting()
        } else if(refreshPostingVersion != null && DataManager.postingVersion.value?:0 > refreshPostingVersion!!){
            mViewModel.onRefreshPosting()
        }
        refreshPostingVersion = DataManager.postingVersion.value
    }

    override fun onDestroy() {
        super.onDestroy()
        animatorHide?.cancel()
        animatorShow?.cancel()
        GlobalContextManager.mainHandler.removeCallbacks(delayFinish)
    }



    var menuModel = 0 // 1 展开态， 2是收起
    var scrollTabModel = 0 // 1 展开态， 2是收起
    private fun updateTitleBar(alpha:Float){
        binding.titleBarBg.alpha = alpha
        binding.campNameTop.alpha = alpha
        if(alpha == 0f){
            if(menuModel != 1){
                binding.back.setImageResource(R.drawable.icon_white_with_black)
                binding.btnCollect.setImageResource(R.drawable.selector_collect_with_back)
                binding.btnShare.setImageResource(R.drawable.icon_share_white_with_black)
                binding.back.layoutParams.height = 28.dp
                binding.back.layoutParams.width = 28.dp
                binding.btnCollect.layoutParams.height = 28.dp
                binding.btnCollect.layoutParams.width = 28.dp
                binding.btnShare.layoutParams.height = 28.dp
                binding.btnShare.layoutParams.width = 28.dp
                menuModel = 1
                binding.titleBarContent.requestLayout()
            }
        } else{
            if(menuModel != 2){
                binding.back.setImageResource(R.drawable.icon_back_black)
                binding.btnCollect.setImageResource(R.drawable.selector_collect)
                binding.btnShare.setImageResource(R.drawable.icon_share_black)
                binding.back.layoutParams.height = 24.dp
                binding.back.layoutParams.width = 24.dp
                binding.btnCollect.layoutParams.height = 24.dp
                binding.btnCollect.layoutParams.width = 24.dp
                binding.btnShare.layoutParams.height = 24.dp
                binding.btnShare.layoutParams.width = 24.dp
                menuModel = 2
                binding.titleBarContent.requestLayout()
            }
        }


        if(alpha == 1f){
            if(scrollTabModel != 1){
                binding.llScrollTab.setBackgroundResource(R.drawable.bg_white_0_0_0_0)
                (binding.llScrollTab.layoutParams as ConstraintLayout.LayoutParams).apply {
                    leftMargin = 0.dp
                    rightMargin = 0.dp
                }
                scrollTabModel = 1
                binding.llScrollTab.requestLayout()
            }

        } else {
            if(scrollTabModel != 2){
                binding.llScrollTab.setBackgroundResource(R.drawable.bg_white_5_5_0_0)
                (binding.llScrollTab.layoutParams as ConstraintLayout.LayoutParams).apply {
                    leftMargin = 8.dp
                    rightMargin = 8.dp
                }
                scrollTabModel = 2
                binding.llScrollTab.requestLayout()
            }
        }
    }

    fun updateTabStatus(){
        val layoutManager: CustomStaggeredGridLayoutManager = binding.recyclerView.layoutManager as CustomStaggeredGridLayoutManager
        val firstVisible = layoutManager.findFirstVisibleItemPositions(null)[0]
        val lastVisible = layoutManager.findLastVisibleItemPositions(null)[0]
        val parametersHeaderPosition = adapter?.getParametersGroupHeaderPosition()?:0
        val appraiseHeaderPosition = adapter?.getAppraiseGroupHeaderPosition()?:0
        val bookingHeaderPosition = adapter?.getBookingGroupHeaderPosition()?:0
        if(firstVisible == 0){
            handleTabSelected(0)
        }else if(adapter?.parametersGroup?.placeDetail != null){
            when {
                firstVisible >= parametersHeaderPosition  -> {
                    handleTabSelected(titles.indexOf(title_detail))
                }
                firstVisible >= appraiseHeaderPosition -> {
                    handleTabSelected(titles.indexOf(title_appraise))
                }
                firstVisible > bookingHeaderPosition -> {
                    handleTabSelected(titles.indexOf(title_booking))
                }
            }
        }

        val introduceHeaderPosition = adapter?.getIntroduceGroupHeaderPosition()?:0
        if(adapter?.parametersGroup?.placeDetail != null && firstVisible >= introduceHeaderPosition){
            binding.btnToTop.visibility = View.VISIBLE
        } else {
            binding.btnToTop.visibility = View.GONE
        }

    }

    private val mFragmentContainerHelper = FragmentContainerHelper()
    var title_booking = "预订"
    var title_appraise = "评价"
    var title_detail = "介绍"
    var titles = mutableListOf<String>(title_detail)
    private fun initMagicIndicator() {
        val magicIndicator = binding.magicIndicator
        val commonNavigator = CommonNavigator(this)
        commonNavigator.notifyDataSetChanged()
        commonNavigator.isAdjustMode = false
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return titles.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val simplePagerTitleView = PlaceDetailPagerTitleView(context)
                simplePagerTitleView.setText(titles.get(index))
                simplePagerTitleView.selectedColor = Color.parseColor("#333333")
                simplePagerTitleView.normalColor = Color.parseColor("#999999")
                simplePagerTitleView.width = UIUtil.dip2px(context, 88.0)
                simplePagerTitleView.setOnClickListener {
                    isTabClick = true
                    currentTabIndex = -1
                    handleTabSelected(index, true)
                }
                return simplePagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = CustomLinePagerIndicator(context)
                indicator.mode = LinePagerIndicator.MODE_EXACTLY
                indicator.setImageSrc(R.drawable.icon_place_detail_tab_index)
                indicator.lineHeight = UIUtil.dip2px(context, 10.0).toFloat()
                indicator.lineWidth = UIUtil.dip2px(context, 44.0).toFloat()
                indicator.setColors(Color.parseColor("#000000"))
                return indicator
            }
        }
        magicIndicator.navigator = commonNavigator
        mFragmentContainerHelper.attachMagicIndicator(magicIndicator)
    }

    private var currentTabIndex = 0
    fun handleTabSelected(index:Int, tabClick:Boolean = false){
        if(currentTabIndex != index && index >= 0){
            currentTabIndex = index
            mFragmentContainerHelper.handlePageSelected(index)
            if(tabClick){
                val title = titles[index]
                when(title){
                    title_booking -> {
                        val position = adapter?.getBookingGroupHeaderPosition()
                        position?.let {
                            scrollToPosition(it)
                        }
                    }
                    title_appraise -> {
                        val position = adapter?.getAppraiseGroupHeaderPosition()
                        position?.let {
                            scrollToPosition(it)
                        }
                    }
                    title_detail -> {
                        val position = adapter?.getParametersGroupHeaderPosition()
                        position?.let {
                            scrollToPosition(it)
                        }
                    }
                }
            }
        }
    }

    fun scrollToPosition(position: Int){
        binding.appBarLayout.setExpanded(false)
        binding.recyclerView.scrollToPosition(position)
        (binding.recyclerView.layoutManager as CustomStaggeredGridLayoutManager).scrollToPositionWithOffset(position, 0)
    }



    fun publishPosting(placeDetail: PlaceDetail){
        LoginActivity.checkLogin(object : ActionAfterLogin {
            override fun action() {
                if(!this@PlaceDetailActivity.isFinishing){
                    val campInfo = CampInfo()
                    campInfo.id = placeDetail.camp?.id
                    campInfo.camp_name = placeDetail.camp?.camp_name
                    campInfo.location_addr = placeDetail.camp?.location_addr
                    campInfo.latitude = placeDetail.camp?.latitude
                    campInfo.longitude = placeDetail.camp?.longitude
                    campInfo.images = placeDetail.camp?.images
                    PostManager.showPostTypeSelector(this@PlaceDetailActivity, campInfo = campInfo)
                }
            }
        })
    }

    fun navigationClick(){
        mViewModel.placeDetail.value?.let {  placeDetail->
            if(placeDetail?.camp?.longitude?.isNotEmpty() == true && placeDetail.camp?.latitude?.isNotEmpty() == true){
                MapActivity.showMapNavigationList(this, placeDetail.camp?.location_addr?:"",
                    placeDetail.camp?.latitude?:"", placeDetail.camp?.longitude?:"", "camp_detail")
            } else {
                val errMsg = GlobalContextManager.getString(R.string.data_error)
                Toast.makeText(GlobalContextManager.appContext, errMsg, Toast.LENGTH_SHORT).show()
            }
        }
    }

    val translationXTarget = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_69)
    var animatorHide : ObjectAnimator? = null
    var animatorShow : ObjectAnimator? = null
    fun startPostingBtnHide() {
        if(binding.btnPosting.translationX != translationXTarget.toFloat() && (animatorHide == null || !animatorHide!!.isRunning)){
            animatorShow?.cancel()
            animatorHide = ObjectAnimator.ofFloat(binding.btnPosting, "translationX", binding.btnPosting.translationX, translationXTarget.toFloat())
            animatorHide?.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {
                    binding.btnPostingImg.setImageResource(R.drawable.icon_place_detail_punch_card)
                }

                override fun onAnimationEnd(animation: Animator) {
                    binding.btnPostingImg.setImageResource(R.drawable.icon_place_detail_punch_card_hide)
                    animatorHide = null
                }

                override fun onAnimationCancel(animation: Animator) {
                    binding.btnPostingImg.setImageResource(R.drawable.icon_place_detail_punch_card)
                }

                override fun onAnimationRepeat(animation: Animator) {
                }

            })
            animatorHide?.addUpdateListener {
            }
            animatorHide?.duration = 500
            animatorHide?.start()
        }

    }

    val showRunnable  = Runnable {
        startPostingBtnShow()
    }

    fun startPostingBtnShow() {
        if(binding.btnPosting.translationX != 0f && (animatorShow == null || !animatorShow!!.isRunning) && binding.recyclerView.scrollState == RecyclerView.SCROLL_STATE_IDLE){
            animatorHide?.cancel()
            animatorShow = ObjectAnimator.ofFloat(binding.btnPosting, "translationX", binding.btnPosting.translationX, 0f)
            animatorShow?.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {
                    binding.btnPostingImg.setImageResource(R.drawable.icon_place_detail_punch_card)
                }

                override fun onAnimationEnd(animation: Animator) {
                    binding.btnPostingImg.setImageResource(R.drawable.icon_place_detail_punch_card)
                    animatorShow = null
                }

                override fun onAnimationCancel(animation: Animator) {
                    binding.btnPostingImg.setImageResource(R.drawable.icon_place_detail_punch_card)
                }

                override fun onAnimationRepeat(animation: Animator) {
                }

            })
            animatorShow?.addUpdateListener {
            }
            animatorShow?.duration = 500
            animatorShow?.start()
        }

    }

    private fun onShare() {
        if(mViewModel.placeDetail.value == null){
            return
        }
        val tools = mutableListOf<ActionItem>()
        if(mViewModel.placeDetail.value?.is_allow_edit == true){
            tools.add(
                ActionItem(
                    R.drawable.icon_share_edit,
                    "编辑营地"
                )
            )
        }
        ShareDialog(this, tools, ShareDialog.CAMP_DETAIL, desc = detailId.toString())
            .setPlaceData(mViewModel.placeDetail.value)
            .setActionCallback {
                when (it) {
                    "编辑营地" -> {
                        if(mViewModel.greenCampAgreeStatus.value != null && mViewModel.greenCampAgreeStatus.value!!.status ==0){
//                            GreenCampEntranceForEditDialog(this, commit = {
//                                it.dismiss()
//                                greenCampLauncher.launch(Intent(this, GreenCampProtocolActivity::class.java).apply {
//                                    putExtra("from", "edit")
//                                })
//                            }).show()
                        } else {
                            openCampUpload()
                        }
                    }
                }
            }
            .show()
    }

    fun openCampUpload(){
        LoginActivity.checkLogin ( object : ActionAfterLogin {
            override fun action() {
            }
        })
    }




    class ImageAdapter : BaseBannerAdapter<ImageInfo>() {

        override fun getLayoutId(viewType: Int): Int {
            return R.layout.item_image_banner_crop
        }

        override fun bindData(
            holder: BaseViewHolder<ImageInfo>,
            data: ImageInfo,
            position: Int,
            pageSize: Int
        ) {
            holder.findViewById<SafetySimpleDraweeView>(R.id.image).setImageURI(getFinalUrl( data.url?:""))
        }

    }

}